#!/usr/bin/env bash
systemctl stop firewalld
systemctl disable firewalld
export Keepalived_IPS='Master=k8s-master-01=172.16.100.31 Slave1=k8s-master-02=172.16.100.32 Slave2=k8s-master-03=172.16.100.33 V1=k8s-master-vip-01=172.16.100.254'
ips='172.16.100.31 172.16.100.32 172.16.100.33'
VIP='172.16.100.254'
i=0
for IP in ${Keepalived_IPS}
do
    i=$((i+1))
    if [ "$i" -ge 4 ];then
        break
    fi
    export $IP
    HOST=`echo $IP |awk -F "=" '{print $1}'`
    IPS=`eval echo '$'$HOST`
    hostname=`echo $IPS |awk -F "=" '{print $1}'`
    hostip=`echo $IPS |awk -F "=" '{print $2}'`
    ct=0
    for ii in $ips;
    do
        ct=$(($ct+1))
        export PL$ct=
        if [[ "$ii" != $hostip ]];then
           export PL$ct="$ii"
        fi
    done
    export KEP_IP=`eval echo '$'{PL1} '$'{PL2} '$'{PL3}`
    echo 地址池:$KEP_IP
    echo 本地IP:"$hostip"
    echo 初始化keeplived $hostip
done

# hostnamectl set-hostname k8s-master-01
yum install -y keepalived
mkdir -p /etc/keepalived
state="MASTER"
netowkrName=ip a |grep "$HOST0" |awk '{print $NF}'
cat > /etc/keepalived/keepalived.conf << EOF
global_defs {
   router_id LVS_k8s
}

vrrp_script checkhaproxy
{
    script "/etc/keepalived/check_nginx.sh"
    interval 5
}

vrrp_instance VI_1 {
    # 注意主备参数选择
    state ${Role}
    # 改成本机网卡名 例如 eth0
    interface ${ETH_INT}
    virtual_router_id 61
    # 非抢占模式
    nopreempt
    # 主高于备, 例如 主 50，备 30
    priority ${priority}
    advert_int 1
    authentication {
    auth_type PASS
    auth_pass awzhXylxy.T
    }
    # 本机内网 IP
    unicast_src_ip 172.16.2.121
    unicast_peer {
    # 注释掉本地IP
    172.16.2.122
    }
    # 内网 VIP
    virtual_ipaddress {
    172.16.2.10
    }

    notify_master "/etc/keepalived/notify_action.sh MASTER"
    notify_backup "/etc/keepalived/notify_action.sh BACKUP"
    notify_fault "/etc/keepalived/notify_action.sh FAULT"
    notify_stop "/etc/keepalived/notify_action.sh STOP"
    garp_master_delay 1
    garp_master_refresh 5
    #改成本机网卡名 例如 eth0
    track_interface {
       ${ETH_INT}
    }

    track_script {
    checkhaproxy
    }
}
EOF